/** 
 * @Title:job计划管理类，负责初始化curator，启动监听Leader Selecter线程  
 * @Desription:job计划管理类，负责初始化curator，启动监听Leader Selecter线程
 * @Company:CSN
 * @ClassName:ScheduleManager.java
 * @Author:Justic
 * @CreateDate:2015-6-30   
 * @UpdateUser:Justic  
 * @Version:0.1 
 *    
 */

package com.justic.zk.quartz;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.justic.zk.quartz.curator.ICuratorWrapper;
import com.justic.zk.quartz.curator.impl.CuratorWrapper;
import com.justic.zk.quartz.curator.support.LeaderSelectorThread;
import com.justic.zk.quartz.support.ZkConfig;

/**
 * @ClassName: ScheduleManager
 * @Description: job计划管理类，负责初始化curator，启动监听Leader Selecter线程
 * @author: Justic
 * @date: 2015-6-30
 * 
 */
public class ScheduleManager {

	private Logger logger = LoggerFactory.getLogger(ScheduleManager.class);

	private ZkConfig zkConfig;
	private ICuratorWrapper curator;
	private LeaderSelectorThread leaderThread;
	// 用于标记是否已初始化
	private boolean initFlag = false;

	private void init() throws Exception {
		// 初始化curator，启动连接zk
		curator = new CuratorWrapper(zkConfig);
		// 在zk上创建节点
		curator.createNode();
		// 添加监听节点变化情况,新增or删除
		curator.addPathChildrenListener();
		// 初始化leaderSelecter线程
		leaderThread = new LeaderSelectorThread(curator);

	}

	/**
	 * 
	 */
	public boolean start() {
		try {
			if (!initFlag) {
				init();
				// 启动线程leaderSelecterListener
				ExecutorService leaderService = Executors.newSingleThreadExecutor();
				leaderService.execute(leaderThread);
				initFlag = true;
			}

		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return initFlag;
	}

	public ZkConfig getZkConfig() {
		return zkConfig;
	}

	public void setZkConfig(ZkConfig zkConfig) {
		this.zkConfig = zkConfig;
	}

	public ICuratorWrapper getCurator() {
		return curator;
	}

	public void setCurator(CuratorWrapper curator) {
		this.curator = curator;
	}

}
